#include "ForgotPasswordDialog.h"
#include <utils.h>
#include <resetpassworddialog.h>
#include <QPropertyAnimation>
#include <QPainter>
#include <QPixmap>
#include <QDebug>
#include <QEvent>
#include <QMouseEvent>

ForgotPasswordDialog::ForgotPasswordDialog(QWidget *parent)
    : QDialog(parent) {
    setWindowTitle("找回密码");

    QLabel *labelUserName = new QLabel("用户名：", this);
    QLabel *labelCode = new QLabel("验证码：", this);
    lineEditUserName = new QLineEdit(this);
    lineEditCode = new QLineEdit(this);
    buttonSubmit = new QPushButton("提交", this);

    buttonSubmit->setStyleSheet(R"(
    QPushButton {
        background-color: #17A2B8; /* 青色背景 */
        color: white; /* 白色文字 */
        border-radius: 10px; /* 圆角 */
        padding: 8px 16px; /* 内边距 */
        font-size: 14px; /* 字体大小 */
    }
    QPushButton:hover {
        background-color: #138496; /* 悬停时的深青色 */
    }
    QPushButton:pressed {
        background-color: #117a8b; /* 按下时的更深青色 */
    }
)");

    QImage captchaImage = generateImageCode(verificationCode);
    QPixmap pixmap = QPixmap::fromImage(captchaImage);
    captchaLabel = new ClickableLabel(this);
    captchaLabel->setPixmap(pixmap);
    captchaLabel->setCursor(Qt::PointingHandCursor);

    QVBoxLayout *layout = new QVBoxLayout(this);
    QHBoxLayout *usernameLayout=new QHBoxLayout();
    QHBoxLayout *codeLayout=new QHBoxLayout();

    usernameLayout->addWidget(labelUserName);
    usernameLayout->addWidget(lineEditUserName);
    codeLayout->addWidget(labelCode);
    codeLayout->addWidget(lineEditCode);
    codeLayout->addWidget(captchaLabel);
    layout->addLayout(usernameLayout);
    layout->addLayout(codeLayout);
    layout->addWidget(buttonSubmit);

    connect(captchaLabel, &ClickableLabel::clicked, this, &ForgotPasswordDialog::refreshCaptcha);
    connect(buttonSubmit, &QPushButton::clicked, this, &ForgotPasswordDialog::verifyCode);

}


void ForgotPasswordDialog::verifyCode() {
    QString username = lineEditUserName->text();
    QString code = lineEditCode->text();

    if (code.toLower() != verificationCode.toLower()) {
        QMessageBox::critical(this, "错误", "验证码错误！");
        return;
    }

    QSettings settings("MyApp", "LoginDemo");
    settings.beginGroup("user");
    if (!settings.childGroups().contains(username)) {
        settings.endGroup();
        QMessageBox::critical(this, "错误", "该账号未注册！");
        return;
    }
    settings.endGroup();

    emit verificationSuccess(username);
    ResetPasswordDialog *resetDialog = new ResetPasswordDialog(username, this);
    resetDialog->exec();
    close();
}

void ForgotPasswordDialog::refreshCaptcha() {
    QImage captchaImage = generateImageCode(verificationCode);
    QPixmap pixmap = QPixmap::fromImage(captchaImage);
    captchaLabel->setPixmap(pixmap);
}
